package com.itheima.filter; /**
 * @author tang
 * @date 2022/11/21 19:11
 */

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginCheckFilter")
public class LoginCheckFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //0.强转两个对象
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //1.截取本次请求的uri
        String uri = req.getRequestURI();
        //2.判断本次请求是否是需要放行处理 /backend/**  /front/** /employee/login /employee/logout
        //3.不需要处理直接放行
        //在spring中 提供一个工具类 AntPathMatcher 路径匹配器 可用用他来直接判断那些路径不需要处理 如果一旦匹配上 就直接放行
        String[] urls = {"/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"};       //声明不需要被过滤拦截的资源

        AntPathMatcher pathMatcher = new AntPathMatcher();
        for (String url : urls) {
            if (pathMatcher.match(url, uri)) {
                chain.doFilter(req, resp);
                return; //跳出方法 代码不再继续向下执行
            }
        }
        //4.需要处理：判断员工是否已经登录【从session中获取保存的员工id】
        Object employeeId = req.getSession().getAttribute("employee");

        //5.1：管理后端登录放行：员工id不为null 说明已经登录 直接放行
        if (employeeId != null) {
            //在放行之前 将登录成功的员工id存入到ThreadLocal中
            BaseContext.setCurrentId((Long) employeeId);

            chain.doFilter(req, resp);
            return; //跳出方法 代码不再继续向下执行
        }

        //5:2：移动用户端登录放行：用户id不为null 说明已经登录 直接放行
        Object userId = req.getSession().getAttribute("user");
        if (userId != null) {
            //在放行之前 将登录成功的用户id存入到ThreadLocal中
            BaseContext.setCurrentId((Long) userId);
            chain.doFilter(req, resp);
            return; //跳出方法 代码不再继续向下执行
        }

        //6.员工id为null   说明未登录   响应未登录结果 前端跳转到登录页面    {"code":0,"msg":"NOTLOGIN"}
        resp.getWriter().print(JSON.toJSONString(R.error("NOTLOGIN")));
    }
}
